package org.huangrui.spark.java.core.rdd.operate.transform;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;

import java.util.Arrays;

/**
 * @Author hr
 * @Create 2024-10-17 16:20
 */
public class Spark10_Operate_Transform_WordCount {
    public static void main(String[] args) {
        final SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("spark");
        final JavaSparkContext jsc = new JavaSparkContext(conf);
        // TODO 分组聚合
        //      1. 读取文件
        final JavaRDD<String> lineRdd = jsc.textFile("data/word.txt");
        //      2. 将文件数据进行分解
        final JavaRDD<String> wordRdd = lineRdd.flatMap(line -> Arrays.asList(line.split(" ")).iterator());
        //      3. 将相同的单词分到一个组中
        //         Hello, Hello, Hello
        //         (Hello, [Hello, Hello, Hello])
        final JavaPairRDD<String, Iterable<String>> wordGroupRdd = wordRdd.groupBy(word -> word);
        //      4. 计算每个单词的组中的数量即可
        JavaPairRDD<String, Integer> mapValues = wordGroupRdd.mapValues(words -> {
            int count = 0;
            for (String word : words) {
                count += 1;
            }
            return count;
        });
        mapValues.collect().forEach(System.out::println);

        jsc.close();
    }
}
